﻿using System.Collections.Generic;
using System;

namespace GameBasic
{
    public static class ExtArray
    {
        public delegate Key KeyGetter<T, out Key>(ref T arg);

        public static bool IsLegalIndex(this Array array, int index)
        {
            return index >= 0 && index < array.Length;
        }

        public static Dictionary<K, V> ToDictionary<K, V>(this V[] array, Func<V, K> keyGetter, Dictionary<K, V> store = null)
        {
            if (store == null)
                store = new Dictionary<K, V>(array.Length);
            
            for (int i = 0, length = array.Length; i < length; i++)
            {
                V item = array[i];
                store[keyGetter(item)] = item;
            }

            return store;
        }

        public static Dictionary<K, V> ToDictionary<K, V>(this V[] array, KeyGetter<V, K> keyGetter, Dictionary<K, V> store = null)
        {
            if (store == null)
                store = new Dictionary<K, V>(array.Length);

            for (int i = 0, length = array.Length; i < length; i++)
            {
                V item = array[i];
                var k = keyGetter(ref item);
                store[k] = item;
            }

            return store;
        }

        public static void ForEach<T>(this T[,] array, Action<int, int, T[,]> action)
        {
            for (int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                {
                    action(i, j, array);
                }
            }
        }
    }
}